package com.cbgolf.oa.model;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cbgolf.oa.base.BaseModel;
import com.cbgolf.oa.presenter.ILoginPresenter;
import com.cbgolf.oa.inteface.INetCallBack;
import com.cbgolf.oa.entity.NetResponse;
import com.cbgolf.oa.entity.ParkBean;
import com.cbgolf.oa.net.NetCallBack;
import com.cbgolf.oa.net.Web;
import com.cbgolf.oa.net.WebAPI;
import com.cbgolf.oa.rsa.RSAUtils;
import com.cbgolf.oa.user.LoginUser;
import com.cbgolf.oa.user.User;
import com.cbgolf.oa.user.UserData;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.ErrorUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.Util;

import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lq on 2017/9/13.
 */

public class LoginModel extends BaseModel {

  private ILoginPresenter worker;

  public LoginModel(ILoginPresenter worker) {
    this.worker = worker;
  }

  public void checkLoginInfo(String account, String pwd, String parkName, String startName) {
    if (Util.isNull(parkName.trim()) && Util.isNull(account)) {
      worker.onError("请输入登录账号");
      return;
    }
    if (Util.isNull(pwd.trim())) {
      worker.onError("请输入登录密码");
      return;
    }
    if (!Util.isNull(parkName.trim()) && Util.isNull(startName) && Util.isNull(account)) {
      searchStartName(account, pwd, parkName);
      return;
    }

    String loginAccount = account;
    if (!Util.isNull(startName)) {
      loginAccount = Util.isNull(account) ? startName : (account.startsWith(startName + ":") ?
          account : (startName + ":" + account));
    }
    LoginUser user = new LoginUser();
    user.setCourseName(TextUtil.Text(parkName));
    user.setAccountChild(TextUtil.Text(account));
    user.setAccountStart(TextUtil.Text(startName));
    user.setLoginAccount(TextUtil.Text(loginAccount));
    UserData.setLoginUser(user);
    getRsa(loginAccount, pwd);
  }


  private void getRsa(final String account, final String pwd) {
    if (!Util.isNetWorkConnected()) {
      worker.onError(ErrorUtil.NONET);
      return;
    }
    String url = WebAPI.pwd_rsa_get;
    worker.showProgress();
    Web.getOK(url, new NetCallBack(response -> {
      if (200 != response.statusCode) {
        worker.stopProgress();
        worker.onError(ErrorUtil.NONET);
        return;
      }
      String exponent;
      String modulus;
//                PublicKey publicKey = null;
      try {
        JSONObject json = JSON.parseObject(response.result);
        exponent = DataUtil.getJsonString(json, "empoent");
        modulus = DataUtil.getJsonString(json, "module");
//                    publicKey = RSAUtils.getPublicKey(modulus, exponent);
//                    publicKey = RSAUtils.loadPublicKey(modulus);
        RSAPublicKey pubkey = RSAUtils.getRSAPublidKey(modulus, exponent);
        String pwdNew = RSAUtils.encryptString(pubkey, pwd);
        Log.e("new pwd--------", pwdNew + "");
        doLogin(account, pwdNew);
      } catch (Exception e) {
        worker.stopProgress();
        worker.onError(ErrorUtil.NETERROR);
        Log.e("catch--------", e.toString());
        return;
      }
    }));


  }

  public void doLogin(final String account, String pwd) {
    String url = WebAPI.login_post;
    Map<String, String> map = new HashMap<>();
    map.put("userAccount", account);
    map.put("password", pwd);
//        AnimaUtil.showLoading(AppManager.getNewInstance().getStaskTopActivity());
    Web.postOk(url, map, new NetCallBack(response -> {
      worker.stopProgress();
      if (200 != response.statusCode) {
        doFail(response);
        return;
      }
      doSuccess(response);
    }));
  }

  private void doSuccess(NetResponse response) {
    try {
      User user = new User();
      user.setToken(response.token);
      UserData.setUser(user);
    } catch (Exception e) {

    }
    if (null != worker) {
      worker.loginSuccess();
    }
  }

  private void doFail(NetResponse response) {
    if (null == worker) {
      worker.onError(ErrorUtil.NETERROR);
      return;
    }
    if (401 == response.statusCode) {
      worker.onError("账户或密码错误");
      return;
    }
    worker.onError(response.errorMsg);
  }

  public void searchPark(final String name) {
    String url = WebAPI.park_search_get;
    Map<String, String> map = new HashMap<>();
    map.put("courseName", TextUtil.Text(name));
    Web.getOK(url, map, new NetCallBack(new INetCallBack() {
      @Override
      public void onResponse(NetResponse response) {
        List<ParkBean> list = null;
        try {
          list = JSON.parseArray(response.result, ParkBean.class);
        } catch (Exception e) {

        }
        if (!Util.listIsNull(list)) {
          worker.getParkSuccess(list, name);
        }
      }
    }));

  }

  private void searchStartName(final String account, final String pwd, final String parkName) {
    String url = WebAPI.park_search_get;
    Map<String, String> map = new HashMap<>();
    map.put("courseName", TextUtil.Text(parkName));
    Web.getOK(url, map, new NetCallBack(new INetCallBack() {
      @Override
      public void onResponse(NetResponse response) {
        List<ParkBean> list = null;
        try {
          list = JSON.parseArray(response.result, ParkBean.class);
        } catch (Exception e) {

        }
        if (Util.listIsNull(list)) {
          worker.stopProgress();
          worker.onError("很抱歉，未找到此球场");
          return;
        }
        String startName = "";
        for (int i = 0; i < list.size(); i++) {
          if (Util.isEquals(parkName, list.get(i).courseName)) {
            startName = list.get(i).userAccount;
            break;
          }
        }
        if (Util.isNull(startName)) {
          worker.stopProgress();
          worker.onError("很抱歉，未找到此球场");
          return;
        }
        checkLoginInfo(account, pwd, parkName, startName);

      }
    }));

  }
}
